define(function(require, exports, module) {
  var dialog = require('dialog');

  module.exports = Backbone.View.extend({
    tagName: 'table',
    className: 'table table-bordered',
    viewData: {},
    Collection: function() {
      return {collection: new Backbone.Collection.extend()};
    },
    ItemView: function(opt) {
      return (new Backbone.View.extend()(opt));
    },
    initialize: function(options) {

      this.prepareViewData();
      this.$el.html( this.template({view: this.viewData}) );

      this.list = this.Collection().collection;
      this.listenTo(this.list, 'add', this.addOne);
      this.listenTo(this.list, 'reset', this.addAll);
      this.listenTo(this.list, 'all', this.render);

    },
    events: { },
    render: function() {
      this.afterRender();

      return this;
    },
    afterRender: function() {},
    prepareViewData: function() { },
    addOne: function(model) {
      var view = this.ItemView({ model: model });
      $(this.el).find('tbody').append(view.render().el);
    },
    addAll: function() {
      this.list.each(this.addOne, this);
    },
    fetch: function(option) {
      option = option || {};
      var data = option.data || {};
      var self = this;
      self.list.fetch({
        data: data,
        success: function(results, resp, opt) {
          if(results.length > 0) {
            self.list.add(results.models);
          }
          if(option.success && _.isFunction(option.success)) option.success(results, resp, opt);
        },
        error: function(obj, resp, opt) {
          dialog.alert(resp.responseText,'获取失败');
          if(option.error && _.isFunction(option.error)) option.error(obj, resp, opt);
        }
      });
    }
  });
});